package cn.com.visionsky.bocsz.bda.webservice.ws;

import cn.com.visionsky.bocsz.bda.webservice.Constants;
import cn.com.visionsky.bocsz.bda.webservice.exception.RequestXmlException;
import cn.com.visionsky.bocsz.bda.webservice.exception.ResponseXmlException;
import cn.com.visionsky.bocsz.bda.webservice.handler.Handler;
import cn.com.visionsky.bocsz.bda.webservice.handler.customer_tags_query.FullTextRequest;
import cn.com.visionsky.bocsz.bda.webservice.permission.CustomerTagsPermission;
import cn.com.visionsky.bocsz.bda.webservice.util.SpringHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.cxf.transport.http.AbstractHTTPDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import java.util.Date;

/**
 * Created by 46043 on 2016/8/2.
 */
@WebService
public class WsControllerImpl implements WsController {
    private static final Logger logger = LoggerFactory.getLogger(WsControllerImpl.class);

    @Resource(name = "org.apache.cxf.jaxws.context.WebServiceContextImpl")
    private WebServiceContext context;

    @Autowired
    private SpringHelper springHelper;

    public Reply route(Application application) {

        MessageContext ctx = context.getMessageContext();
        HttpServletRequest request = (HttpServletRequest) ctx.get(AbstractHTTPDestination.HTTP_REQUEST);

        /**
         * 组织回复报文的报文头
         */
        final Reply reply = new Reply();
        reply.setMsgId(application.getMsgId());
        reply.setSysId(application.getSysId());
        reply.setUid(application.getUid());
        reply.setSrlNum(application.getSrlNum());
        reply.setTxnDate(DateFormatUtils.format(new Date(), "yyyyMMDD"));
        reply.setTxnCode(application.getTxnCode());
        reply.setInstNo(application.getInstNo());
        reply.setUsrId(application.getUsrId());
        reply.setUsrBrnh(application.getUsrBrnh());

        //update by 周秋福 start
        final String clientIp = request.getRemoteAddr();
        final String requestFullText = application.getFullTxt();//请求参数

        final String historyTransQueryHandler = "1000000001";
        final String customerTagsQueryHandler = "1000000002";
        final String cstLblAsQueryHandler = "1000000003";

        final String historyTransQueryModule = "historyTransQueryHandler";
        final String customerTagsQueryModule = "customerTagsQueryHandler";
        final String cstLblAstQueryModule = "cstLblAstQueryHandler";


        String handlerBeanId = application.getTxnCode();
        if (StringUtils.isBlank(handlerBeanId)) {
            reply.setResultCode(Constants.TXN_CODE_IS_BLANK_CODE);
            reply.setResultMsg(Constants.TXN_CODE_IS_BLANK_MSG);
            return reply;
        }

        handlerBeanId = handlerBeanId.trim();

        switch (handlerBeanId) {
            case historyTransQueryHandler:
                handlerBeanId = historyTransQueryModule;
                break;

            case customerTagsQueryHandler:
                handlerBeanId = customerTagsQueryModule;
                break;

            case cstLblAsQueryHandler:
                handlerBeanId = cstLblAstQueryModule;

            default:
                break;
        }


        FullTextRequest fullTextRequest = FullTextUtils.getFullTextRequest(FullTextRequest.class, requestFullText);
        cn.com.visionsky.bocsz.bda.webservice.handler.cst_lbl_ast_query.FullTextRequest cstFullTextRequest =
                FullTextUtils.getFullTextRequest(cn.com.visionsky.bocsz.bda.webservice.handler.cst_lbl_ast_query.FullTextRequest.class, requestFullText);

        //字段权限控制器//授权不通过直接返回拒绝信息
        switch (handlerBeanId) {
            case Constants.HISTORY_TRANS_QUERY_HANDLER_MODULE://历史信息查询模块
                //请求参数暂时不添加权限管控
                break;

            case Constants.CUSTOMER_TAGS_QUERY_HANDLER_MODULE://客户标签查询模块

                //必填字段校验
                //mode(客户号模式或客户证件号模式)
                //cstId
                //ctfNo
                String mode = fullTextRequest.getMode();
                if (StringUtils.isBlank(mode)) {
                    reply.setResultCode(Constants.MODE_TAG_IS_REQUIRED_CODE);
                    reply.setResultMsg(Constants.MODE_TAG_IS_REQUIRED_MSG);
                    return reply;
                }

                switch (mode) {
                    case Constants.CST_ID_MODE://客户号模式
                        String cstId = fullTextRequest.getCstId();
                        if (StringUtils.isBlank(cstId)) {
                            reply.setResultCode(Constants.CST_ID_TAG_IS_REQUIRED_CODE);
                            reply.setResultMsg(Constants.CST_ID_TAG_IS_REQUIRED_MSG);
                            return reply;
                        }
                        break;

                    case Constants.CTF_NO_MODE://客户证件号模式
                        String ctfNo = fullTextRequest.getCtfNo();
                        if (StringUtils.isBlank(ctfNo)) {
                            reply.setResultCode(Constants.CTF_NO_TAG_IS_REQUIRED_CODE);
                            reply.setResultMsg(Constants.CTF_NO_TAG_IS_REQUIRED_MSG);
                            return reply;
                        }
                        break;

                    default:
                        break;
                }

                //请求参数添加权限管控
                CustomerTagsPermission customerTagsPermission = new CustomerTagsPermission(fullTextRequest, clientIp);
                Reply resultReply = customerTagsPermission.verifyCustomerTagsPermission();
                if (StringUtils.equals(resultReply.getResultCode(), Constants.PERMISSION_DENIED_CODE)) {//Permission denied
                    reply.setResultCode(resultReply.getResultCode());
                    reply.setResultMsg(resultReply.getResultMsg());
                    return reply;
                }
                break;

            case Constants.CST_LBL_AST_QUERY_MODULE: //新证件号查询模块
                String newctfNo = cstFullTextRequest.getCtfNo();
                if (StringUtils.isBlank(newctfNo)) {
                    reply.setResultCode(Constants.CTF_NO_TAG_IS_REQUIRED_CODE);
                    reply.setResultMsg(Constants.CTF_NO_TAG_IS_REQUIRED_MSG);
                    return reply;
                }
                break;

            default:
                break;
        }
        //update by 周秋福 start

        Handler handler = springHelper.getHandler(handlerBeanId);

        logger.info(String.format("handler bean %s found，begin handle:", handlerBeanId));
        try {
            final String fullTxt = handler.handle(requestFullText, request);
            reply.setFullTxt(fullTxt);
            reply.setResultCode(Constants.RESULT_CODE_SUCCESS);
            reply.setResultMsg(Constants.RESULT_MSG_SUCCESS);
            logger.info(Constants.RESULT_MSG_SUCCESS);
        } catch (RequestXmlException e) {
            reply.setResultCode(Constants.RESULT_CODE_FAIL_REQUEST_XML_EXCEPTION);
            reply.setResultMsg(e.getMessage());
            logger.info(e.getMessage(), e);
        } catch (ResponseXmlException e) {
            reply.setResultCode(Constants.RESULT_CODE_FAIL_RESPONSE_XML_EXCEPTION);
            reply.setResultMsg(e.getMessage());
            logger.info(e.getMessage(), e);
        } catch (Exception e) {
            reply.setResultCode(Constants.RESULT_CODE_FAIL_UNKNOWN_EXCEPTION);
            reply.setResultMsg("unknown exception");
            logger.info(e.getMessage(), e);
        }

        return reply;
    }

}
